//
//  FTYHTTPManager.m
//  RedWine
//
//  Created by Liufangfang on 2016/12/31.
//  Copyright © 2016年 HuiBangKe. All rights reserved.
//

#import "FTYHTTPManager.h"

@implementation FTYHTTPManager

#pragma mark - Init Method

- (instancetype)init{
    
    if (self = [super init]) {
        _baseUrl = [NSURL URLWithString:EP_SERVER_HOST];
    }
    return self;
}

#pragma mark - Public Method

+ (AFHTTPSessionManager *)sharedManager{
    
    static FTYHTTPManager *manager = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        manager = [[self alloc] init];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //请求序列化处理
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        //响应序列化处理
        AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
        //移除JSON块中的null值及其对应key
        responseSerializer.removesKeysWithNullValues = YES;
        responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html", nil];
        manager.responseSerializer = responseSerializer;
    });
    
    return manager;
}

+ (AFHTTPSessionManager *)sharedManagerWithJsonNull{
    
    static FTYHTTPManager *manager = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        manager = [[self alloc] init];
        //请求序列化处理
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    });
    
    return manager;
}

+ (void)checkNetworkStatus{
    
    //1.获得网络监控的管理者
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    
    //2.设置网络状态改变后的处理
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //当网络状态改变了，就会调用这个block
        switch (status) {
                
            case AFNetworkReachabilityStatusUnknown:    // 未知网络
                NSLog(@"未知网络！");
                break;
            case AFNetworkReachabilityStatusNotReachable:   // 没有网络(断网)
                NSLog(@"没有网络！（断网）");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:   // WIFI
                NSLog(@"Wi-Fi");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:   // 手机自带网络
                NSLog(@"手机自带网络");
                break;
            default:
                break;
        }
    }];
    
    //3.开始监控
    [reachabilityManager startMonitoring];
}

//Get请求方法
+ (void)getInfoWithSubUrl:(NSString *)subUrl parameters:(NSDictionary *)parameters block:(void (^)(id, NSError *))block{
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", EP_SERVER_HOST, subUrl];
    DLog(@"rqURL:%@",requestUrl);
    if ([subUrl hasPrefix:@"http://"]) {
        requestUrl = subUrl;
    }
    
    [[[self class] sharedManager] GET:requestUrl parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
        NSLog(@"downloadProgress: %@", downloadProgress);
        if (block && downloadProgress) {
            
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        block(responseObject, nil);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (block) {
            block(nil, error);
        }
    }];
}

//Post请求方法
+ (void)postInfoWithSubUrl:(NSString *)subUrl parameters:(NSDictionary *)parameters block:(void (^)(id, NSError *))block{
    
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", EP_SERVER_HOST, subUrl];
    NSLog(@"rqURL:%@",requestUrl);
    if ([subUrl hasPrefix:@"http://"]) {
        requestUrl = subUrl;
    }
    //请求中包含中文，需要如下处理，否则崩溃
    requestUrl = [requestUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [[[self class] sharedManager] POST:requestUrl parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {

        if (block && uploadProgress) {
            
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (block && responseObject) {
            block(responseObject, nil);
        }
    } failure:^(NSURLSessionDataTask *   task, NSError * _Nonnull error) {
        
        if (block) {
            block(nil, error);
        }
    }];
}

+ (void)cancelRequest{
    //TODO：找更好的方法
    NSLog(@"取消网络请求");
    [[[[self class] sharedManager] operationQueue] cancelAllOperations];
}

@end
